package org.jeecg.modules.zcglRecipients.controller;

import java.beans.Transient;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.var;
import org.jeecg.modules.activiti.entity.ActBusiness;
import org.jeecg.modules.activiti.service.IActBusinessService;
import org.jeecg.modules.putstorage.entity.ZcglPutStorage;
import org.jeecg.modules.putstorage.util.Serialnumber;
import org.jeecg.modules.zcgl.entity.AssetFixed;
import org.jeecg.modules.zcgl.service.IAssetFixedService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.zcglRecipients.entity.ZcglRecipientsAssets;
import org.jeecg.modules.zcglRecipients.entity.ZcglRecipients;
import org.jeecg.modules.zcglRecipients.vo.ZcglRecipientsPage;
import org.jeecg.modules.zcglRecipients.service.IZcglRecipientsService;
import org.jeecg.modules.zcglRecipients.service.IZcglRecipientsAssetsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 资产领用
 * @Author: jeecg-boot
 * @Date:   2022-10-24
 * @Version: V1.0
 */
@Api(tags="资产领用")
@RestController
@RequestMapping("/zcglRecipients/zcglRecipients")
@Slf4j
public class ZcglRecipientsController {
	@Autowired
	private IZcglRecipientsService zcglRecipientsService;
	 @Autowired
	 private IActBusinessService actBusinessService;
	 @Autowired
	 private IAssetFixedService iAssetFixedService;

	@Autowired
	private IZcglRecipientsAssetsService zcglRecipientsAssetsService;

	/**
	 * 分页列表查询
	 *
	 * @param zcglRecipients
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "资产领用-分页列表查询")
	@ApiOperation(value="资产领用-分页列表查询", notes="资产领用-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZcglRecipients zcglRecipients,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		if(zcglRecipients.getAssetId()!=null){
			//代表有物资，走另外一条sql查询
			Page<ZcglRecipients> page = new Page<ZcglRecipients>(pageNo, pageSize);
			Map map = new HashMap();
			map.put("id",zcglRecipients.getAssetId());
			map.put("recipientsUser",zcglRecipients.getRecipientsUser());
			map.put("newDepartment",zcglRecipients.getNewDepartment());
			map.put("curPage",(page.getCurrent() - 1) * page.getSize());
			map.put("pageSize",page.getSize());
			List<ZcglRecipients> list = zcglRecipientsService.listByAsset(map);
			page.setRecords(list);
			return Result.ok(page);
		}

        Map map =  req.getParameterMap();
//		map.put("delFlag","0");
		QueryWrapper<ZcglRecipients> queryWrapper = QueryGenerator.initQueryWrapper(zcglRecipients,map);
		queryWrapper.eq("del_flag","0");
		queryWrapper.eq("process_status","2");
		Page<ZcglRecipients> page = new Page<ZcglRecipients>(pageNo, pageSize);
		IPage<ZcglRecipients> pageList = zcglRecipientsService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	 /**
	  *   添加
	  *
	  * @param zcglRecipientsPage
	  * @return
	  */
	 @AutoLog(value = "资产领用-添加")
	 @ApiOperation(value="资产领用-添加", notes="资产领用-添加")
	 @PostMapping(value = "/adda")
	 @Transactional
	 public Result<?> adda(@RequestBody ZcglRecipientsPage zcglRecipientsPage) {
		 ZcglRecipients zcglRecipients = new ZcglRecipients();
		 BeanUtils.copyProperties(zcglRecipientsPage, zcglRecipients);
		 int count = zcglRecipientsService.totayCount() + 1;
		 String code = "";
		 String type = "WZLY";
		 if (count < 10) {
			 code = type + Serialnumber.getStringDate() + "00" + count;
		 } else {
			 code = type + Serialnumber.getStringDate() + "0" + count;
		 }
		 zcglRecipients.setOrderNo(code);
		 //默认为启动哦 ，所以设置状态为1 原先是为草稿就是-1
		 zcglRecipients.setProcessStatus(2);
		 //0 代表没删除
		 zcglRecipients.setDelFlag("0");

		 for (int i = 0; i < zcglRecipientsPage.getZcglRecipientsAssetsList().size(); i++) {
			 AssetFixed assetFixed = iAssetFixedService.getById(zcglRecipientsPage.getZcglRecipientsAssetsList().get(i).getAssetId());
			 assetFixed.setAmount(assetFixed.getAmount().subtract(zcglRecipientsPage.getZcglRecipientsAssetsList().get(i).getAssetAmount()));
			 iAssetFixedService.updateById(assetFixed);
		 }
		 String id = zcglRecipientsService.saveMain(zcglRecipients, zcglRecipientsPage.getZcglRecipientsAssetsList());
		 return Result.ok(zcglRecipients,"该类别为自动入库，不需要审批，领用单生成成功！");
	 }
	/**
	 *   添加
	 *
	 * @param zcglRecipientsPage
	 * @return
	 */
	@AutoLog(value = "资产领用-添加")
	@ApiOperation(value="资产领用-添加", notes="资产领用-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ZcglRecipientsPage zcglRecipientsPage) {
		ZcglRecipients zcglRecipients = new ZcglRecipients();
		BeanUtils.copyProperties(zcglRecipientsPage, zcglRecipients);
		int count = zcglRecipientsService.totayCount() + 1;
		String code = "";
		String type = "WZLY";
		if (count < 10) {
			code = type + Serialnumber.getStringDate() + "00" + count;
		} else {
			code = type + Serialnumber.getStringDate() + "0" + count;
		}
		zcglRecipients.setOrderNo(code);
		//默认为启动哦 ，所以设置状态为1 原先是为草稿就是-1
		zcglRecipients.setProcessStatus(1);
		//0 代表没删除
		zcglRecipients.setDelFlag("0");



		String id = zcglRecipientsService.saveMain(zcglRecipients, zcglRecipientsPage.getZcglRecipientsAssetsList());
		return Result.ok(zcglRecipients,"添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param zcglRecipientsPage
	 * @return
	 */
	@AutoLog(value = "资产领用-编辑")
	@ApiOperation(value="资产领用-编辑", notes="资产领用-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ZcglRecipientsPage zcglRecipientsPage) {
		ZcglRecipients zcglRecipients = new ZcglRecipients();
		BeanUtils.copyProperties(zcglRecipientsPage, zcglRecipients);
		ZcglRecipients zcglRecipientsEntity = zcglRecipientsService.getById(zcglRecipients.getId());
		if(zcglRecipientsEntity==null) {
			return Result.error("未找到对应数据");
		}
		zcglRecipientsService.updateMain(zcglRecipients, zcglRecipientsPage.getZcglRecipientsAssetsList());
		return Result.ok(zcglRecipientsEntity,"编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "资产领用-通过id删除")
	@ApiOperation(value="资产领用-通过id删除", notes="资产领用-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		zcglRecipientsService.delMain(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "资产领用-批量删除")
	@ApiOperation(value="资产领用-批量删除", notes="资产领用-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zcglRecipientsService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "资产领用-通过id查询")
	@ApiOperation(value="资产领用-通过id查询", notes="资产领用-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ZcglRecipients zcglRecipients = zcglRecipientsService.getById(id);
		if(zcglRecipients==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(zcglRecipients);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "资产领用记录表通过主表ID查询")
	@ApiOperation(value="资产领用记录表主表ID查询", notes="资产领用记录表-通主表ID查询")
	@GetMapping(value = "/queryZcglRecipientsAssetsByMainId")
	public Result<?> queryZcglRecipientsAssetsListByMainId(@RequestParam(name="id",required=true) String id) {

		//需要去计算仓库真实可以取出的数量
		List<ZcglRecipientsAssets> zcglRecipientsAssetsList = zcglRecipientsAssetsService.selectByMainId(id);
		for (int i = 0; i < zcglRecipientsAssetsList.size(); i++) {
			var item = zcglRecipientsAssetsList.get(i);
			AssetFixed assetFixed = iAssetFixedService.getById(item.getAssetId());
			List<ActBusiness> list = actBusinessService.list(new QueryWrapper<ActBusiness>().eq("status", "1").eq("table_name", "zcgl_put_storage").like("data", assetFixed.getId()));
			if (list.size() > 0) {
				Double count = 0.0 ;
				for (int j = 0; j < list.size(); j++) {
					ActBusiness actBusiness = list.get(j);
					JSONObject data = JSON.parseObject(actBusiness.getData());
					JSONArray jsonArray = data.getJSONArray("zcglPutStorageAssetsList");
					for (int k = 0; k < jsonArray.size(); k++) {
						count += Double.valueOf(jsonArray.getJSONObject(k).get("assetAmount").toString());
					}
				}
				//显示流程中的数量
				assetFixed.setLcCount(new BigDecimal(count));
				//显示可以入库的数量 因为有的在流程中审核，已经被占用数量
				assetFixed.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
				item.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
			}else{
				assetFixed.setTrueCount(assetFixed.getAmount());
				assetFixed.setLcCount(new BigDecimal(0.0));

				item.setTrueCount(assetFixed.getAmount());
			}



		}

		System.out.println("zcglRecipientsAssetsList"+zcglRecipientsAssetsList);
		return Result.ok(zcglRecipientsAssetsList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param zcglRecipients
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZcglRecipients zcglRecipients) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<ZcglRecipients> queryWrapper = QueryGenerator.initQueryWrapper(zcglRecipients, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<ZcglRecipients> queryList = zcglRecipientsService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<ZcglRecipients> zcglRecipientsList = new ArrayList<ZcglRecipients>();
      if(oConvertUtils.isEmpty(selections)) {
          zcglRecipientsList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          zcglRecipientsList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<ZcglRecipientsPage> pageList = new ArrayList<ZcglRecipientsPage>();
      for (ZcglRecipients main : zcglRecipientsList) {
          ZcglRecipientsPage vo = new ZcglRecipientsPage();
          BeanUtils.copyProperties(main, vo);
          List<ZcglRecipientsAssets> zcglRecipientsAssetsList = zcglRecipientsAssetsService.selectByMainId(main.getId());
          vo.setZcglRecipientsAssetsList(zcglRecipientsAssetsList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "资产领用列表");
      mv.addObject(NormalExcelConstants.CLASS, ZcglRecipientsPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("资产领用数据", "导出人:"+sysUser.getRealname(), "资产领用"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ZcglRecipientsPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ZcglRecipientsPage.class, params);
              for (ZcglRecipientsPage page : list) {
                  ZcglRecipients po = new ZcglRecipients();
                  BeanUtils.copyProperties(page, po);
                  zcglRecipientsService.saveMain(po, page.getZcglRecipientsAssetsList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }

}
